package edu.xidian.onlinedocument.utils.ot.internal;

import edu.xidian.onlinedocument.utils.ot.internal.operations.*;

import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class Merge {
    private Merge() {}

    public static ChangesList merge(ChangesList changesList) {
        int i = 0;
        Change first = null;
        Change second = null;

        List<Change> changeList = changesList.getChanges();
        // changeList的size会随着while循环的执行而减小
        while (i < changeList.size() - 1) {
            first = changeList.get(i);
            second = changeList.get(i + 1);

            if (ChangeType.isRetain(first) && ChangeType.isRetain(second)) {
                changeList.remove(i + 1);
                changeList.set(i, new Retain(first.offset() + second.offset()));
            }
            else if (ChangeType.isInsert(first) && ChangeType.isInsert(second)) {
                changeList.remove(i + 1);
                changeList.set(i, new Insert(first.value() + second.value()));
            }
            else if (ChangeType.isDelete(first) && ChangeType.isDelete(second)) {
                changeList.remove(i + 1);
                changeList.set(i, new Delete(first.offset() + second.offset()));
            }
            else {
                i++;
            }
        }
        return changesList;
    }
}
